﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;

namespace SmartFramework.Core.Utils {
	public class TempFileUtil : IDisposable
	{
		readonly string mFolder;
		public TempFileUtil(string folder)
		{
			if (!FS.DirectoryExists(folder)) {
				FS.CreateDirectory(folder);
			} else {
				_idCounter = InitID(folder);
			}
			mFolder = folder;
		}

		bool IsCurrentFolder(string folder) {
			var pathSeps = new[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar };
			int idx1 = folder.LastIndexOfAny(pathSeps, folder.Length - 1);
			int idx2 = folder.LastIndexOfAny(pathSeps, idx1 - 1);
			var curLevel1 = GetLevel1((uint)_idCounter).ToString();
			return folder.Substring(idx2 + 1, idx1 - idx2 - 1) == curLevel1;
		}

		static uint GetLevel1(uint fid) {
			return (fid & 0xffff0000) >> 16;
		}

		static uint GetLevel2(uint fid) {
			return (fid & 0x0000ff00) >> 8;
		}

		static uint GetLevel3(uint fid) {
			return fid & 0xff;
		}

		private int InitID(string folder) {
			string[] dirs = FS.GetDirectories(folder);

			uint result = 0;
			foreach (string dir in dirs) {
				uint rootPageID;
				if (uint.TryParse(Path.GetFileName(dir), out rootPageID)) {
					if (rootPageID > result)
						result = rootPageID;
				}
			}

			return (int)ToLevel1(result + 1);
		}

		private static uint ToLevel1(uint id) {
			return id << 16;
		}
		private int _idCounter;

		public uint NewID()
		{
			/*1.Interlocked 自由锁 
			 *2.还有其它锁 Monitor(监视器）和互斥锁（lock） 
			 *3.读写锁（ReadWriteLock)
			 *4.系统内核对象 
					1) 互斥(Mutex), 信号量(Semaphore), 事件(AutoResetEvent/ManualResetEvent) 
					2) 线程池 
		 */
			return (uint) Interlocked.Increment(ref _idCounter);
		}

		//回收处理
		public void Dispose() {
			
		}
	}
}
